// 拿到数组原型上的方法
let oldArrayProtoMethods = Array.prototype

// 原型继承 arrayMethods.__proto__ = oldArrayProtoMethods
export let arrayMethods = Object.create(oldArrayProtoMethods)

let methods = [
    'push',
    'pop',
    'shift',
    'unshift',
    'reverse',
    'sort',
    'splice'
]

methods.forEach(method => {
    arrayMethods[method] = function(...args) {
        console.log('数组调用');
        // this为observer里面的value
        const result = oldArrayProtoMethods[method].apply(this, args);

        let inserted;
        let ob = this.__ob__;
        switch (method) {
            case 'push':
            case 'unshift':
                // 如果追加的内容也是对象，需要再次进行对象劫持
                inserted = args;
                break;
            case 'splice':
                // 截取参数下标为2到末尾：arr.splice(0, 1, {a: 1})
                inserted = args.slice(2);
            default:
                break;
        }

        // 如果给数组新增的值是对象要继续进行观测
        if (inserted) ob.observeArray(inserted)

        return result
    }
})